/**
* All Rights Reserved , Copyright (C) 2021 , 青岛鼎信通讯股份有限公司
*
* MpmProjectTaskCloseService
* 项目任务关闭
*
* 修改纪录
* 2021-10-09 版本：1.0 zhangqianbo 创建。
* @version 版本：1.0
* @author 作者：zhangqianbo
* 创建日期：2021-10-09
*/
package com.topscomm.mpm.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.topscomm.basic.BasicEntity;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.basic.util.PrimaryKeyUtil;
import com.topscomm.cbo.service.impl.CboAttachmentService;
import com.topscomm.mpm.MpmSystemConst;
import com.topscomm.mpm.pojo.MpmProjectTaskCloseEntity;
import com.topscomm.mpm.pojo.MpmProjectTaskFeedbackEntity;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.SpringUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.tap.TapEntity;
import com.topscomm.tap.common.FlowDatacodeCache;
import com.topscomm.tap.common.SessionUserBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.topscomm.mpm.service.IMpmProjectTaskCloseService;
import com.topscomm.mpm.service.impl.auto.MpmProjectTaskCloseServiceAuto;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service(value = "mpmProjectTaskCloseService")
@Scope(value = "singleton")
public class MpmProjectTaskCloseService extends MpmProjectTaskCloseServiceAuto implements IMpmProjectTaskCloseService {

    FlowDatacodeCache flowDatacodeCache = new FlowDatacodeCache();
    protected List<Map<String, Object>> flowidList = new ArrayList();
    @Autowired
    private CboAttachmentService cboAttachmentService;

    /**
     * @author: zhangqianbo
     * @date:
     * @param entity
     * @throws ServiceException
     * @description:单号生成
     * @modify:
     */
    @Override
    protected void beforeInsert(BasicEntity entity) {
        super.beforeInsert(entity);
        if (entity.getId() <= 0) {// 赋值Id和单号
            long[] arrayId = PrimaryKeyUtil.GeneIDs(entity.getTableName(), 1);
            entity.setId(arrayId[0]);
            String docNo = String.valueOf(arrayId[0]);
            docNo = docNo.substring(0, 6) + docNo.substring(9);
            entity.setValue(MpmProjectTaskCloseEntity.FieldDocno, docNo);
        }
    }

    /**
     * @author: zhangqianbo
     * @date:
     * @param entity
     * @throws ServiceException
     * @description:
     * @modify:
     */
    @Override
    protected void beforeSubmit(TapEntity entity, SessionUserBean sessionUserBean) {
        super.beforeSubmit(entity, sessionUserBean);
        MpmProjectTaskCloseEntity mpmProjectTaskCloseEntity = (MpmProjectTaskCloseEntity) entity;
        this.flowidList = flowDatacodeCache.getApprovalFlowListMap("ApprovalFlow_MpmProjectTaskClose",
                mpmProjectTaskCloseEntity.getApplyusercode(), "sortcode");
        if (flowidList.size() > 0) {// 赋值审批流程id
            mpmProjectTaskCloseEntity.setFlowid(ConvertUtil.convertToLong(flowidList.get(0).get("id")));
        } else {
            throw new ServiceException("没有匹配的审批流，请联系管理员！");
        }
        // 判断是否有审批中的单据，有则不让提交
        String taskid = ConvertUtil.convertToString(mpmProjectTaskCloseEntity.getTaskid());
        long id =mpmProjectTaskCloseEntity.getId();
        StringBufferProxy whereSql = new StringBufferProxy();
        whereSql.appendLineSingle(" taskid='{0}' and id != {1} and state = 1", taskid,id);
        List<MpmProjectTaskCloseEntity> mpmProjectTaskCloseEntities = this.queryByWhere(whereSql.toString());
//        if(mpmProjectTaskCloseEntities.size()>0) {
//            throw new ServiceException("存在仍在审核中的“申请关闭”单据，请等待审核完毕后再新增“申请关闭”单据！");
//        }
        // 判断项目任务反馈的进度是否达到100%，如果到达，不允许异常关闭
        whereSql.clear();
        whereSql.appendLineSingle(" taskid='{0}'", taskid);
        MpmProjectTaskFeedbackService mpmProjectTaskFeedbackService = (MpmProjectTaskFeedbackService) SpringUtil
                .getBean("mpmProjectTaskFeedbackService");
        List<MpmProjectTaskFeedbackEntity> mpmProjectTaskFeedbackEntities = mpmProjectTaskFeedbackService.queryByWhere(whereSql.toString());
        for (MpmProjectTaskFeedbackEntity mpmProjectTaskFeedbackEntity : mpmProjectTaskFeedbackEntities) {
            if ("100".equals(mpmProjectTaskFeedbackEntity.getTaskschedule())) {
                throw new ServiceException("任务进度已达到100%，无需申请异常关闭！");
            }
        }
        // 判断里程碑责任人是否离职，如果已离职需要先变更里程碑责任人
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" mpmprojecttask.id = '{0}' and mpmprojectmilepost.enabled = 1 and cbouser.enabled = 1 ", taskid);
        List<Map<String, Object>> responseList = mpmProjectTaskFeedbackService.queryMapByWhere(sql.toString(), "queryMilepostResponse");
        if (responseList.size() == 0) {
            throw new ServiceException("该任务对应的里程碑责任人已离职，请联系项目经理进行变更。");
        }
    }
    /**
     * @Title: deleteBefore
     * @description: 任务反馈删除时，级联删除存在的任务反馈附件及审批流程
     * @param whereSql
     * @return
     * @author: houyuhang
     * @date: 2021年11月12日
     * @modify:
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    protected void deleteBefore(String whereSql) {
        super.deleteBefore(whereSql);
        //找到删除的一条或多条任务关闭
        List<MpmProjectTaskCloseEntity> mpmProjectTaskCloseEntities = this.queryByWhere(whereSql);
        if (CollectionUtil.isEmpty(mpmProjectTaskCloseEntities)) {
            return;
        }
        // 如果删除了任务关闭，需要同步删除任务反馈关联的任务关闭附件及审批流程
        String taskStr = mpmProjectTaskCloseEntities.stream().map(item -> ConvertUtil.convertToString(item.getId())).collect(Collectors.joining(","));
        if (StringUtil.isEmpty(taskStr)) {
            return;
        }
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" sourcetype = '{0}' and sourceid in ({1}) ", MpmProjectTaskCloseEntity.tableName, taskStr);
        cboAttachmentService.deleteByWhere(sql.toString());
        // 删除flowins和nodeins表信息
        delCboApprovalInsInfo(MpmProjectTaskCloseEntity.tableName, taskStr);
    }
}
